package com.zhouyu.mybatis.mybatis;

import com.zhouyu.mybatis.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author by gang.Li 2022/4/7 14:02
 */
public class MybatisFactoryBean implements FactoryBean {

	private Class interfaceClass;

	public MybatisFactoryBean(Class interfaceClass) {
		this.interfaceClass = interfaceClass;
	}

	private SqlSession sqlSession;

//	@Autowired
	public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
		// Error creating bean with name 'userMapper': FactoryBean threw exception on object creation; nested exception is org.apache.ibatis.binding.BindingException: Type interface com.assumejson.mybatis.mapper.UserMapper is not known to the MapperRegistry.
		// 该错误是Mybatis 没有映射的关系
		sqlSessionFactory.getConfiguration().addMapper(interfaceClass);
		this.sqlSession = sqlSessionFactory.openSession();
	}

	@Override
	public Object getObject() throws Exception {
		// 代理交由mybatis 完成
		return sqlSession.getMapper(interfaceClass);
	}

	@Override
	public Class<?> getObjectType() {
		return interfaceClass;
	}
}
